# coding=utf-8
#


import os
import sys
import json
import time
from datetime import datetime

from django.conf import settings

from django.core.management.base import BaseCommand

from iminer.utils import check_pid

from iminer.agent.models import Agent

from iminer.sm_log import getLogger


logger = getLogger("iminer.agent.management.commands.cron_sync_agent_from_primary_db")


class Command(BaseCommand):
    help = "定时同步agent数据"

    def handle(self, *args, **options):
        """ 定时遍历agent，发现异常agent """
        task_name = "pid/cron_sync_agent_from_primary_db"

        try:
            old_pid = int(open(task_name).read())
        except FileNotFoundError:
            old_pid = 0
        except ValueError:
            old_pid = 0

        cur_pid = os.getpid()
        if not old_pid or not check_pid(old_pid):
            with open(task_name, "w") as fp:
                fp.write(str(cur_pid))

            # 开始
            for agent in Agent.objects.using("primary").filter():
                print(agent.id)
                cur_agent, _ = Agent.objects.get_or_create(idc=agent.idc, alias=agent.alias, ip=agent.ip, cpu=agent.cpu)
                cur_agent.local_its = agent.local_its
                cur_agent.local_avg_its = agent.local_avg_its
                cur_agent.server_id = agent.server_id
                cur_agent.project_id = agent.project_id
                cur_agent.az = agent.az
                cur_agent.last_active = agent.last_active
                cur_agent.status = agent.status
                cur_agent.save()
